package com.tsingteng.cosfun.ui.costar;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.Activity;

import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.media.AudioFormat;
import android.opengl.GLSurfaceView;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.faceunity.beautycontrolview.FURenderer;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.entity.LocalMedia;
import com.qiniu.pili.droid.shortvideo.PLAudioEncodeSetting;
import com.qiniu.pili.droid.shortvideo.PLBuiltinFilter;
import com.qiniu.pili.droid.shortvideo.PLCameraPreviewListener;
import com.qiniu.pili.droid.shortvideo.PLCameraSetting;
import com.qiniu.pili.droid.shortvideo.PLDisplayMode;
import com.qiniu.pili.droid.shortvideo.PLFocusListener;
import com.qiniu.pili.droid.shortvideo.PLMicrophoneSetting;
import com.qiniu.pili.droid.shortvideo.PLRecordSetting;
import com.qiniu.pili.droid.shortvideo.PLRecordStateListener;
import com.qiniu.pili.droid.shortvideo.PLShortVideoComposer;
import com.qiniu.pili.droid.shortvideo.PLShortVideoRecorder;
import com.qiniu.pili.droid.shortvideo.PLShortVideoTranscoder;
import com.qiniu.pili.droid.shortvideo.PLVideoEncodeSetting;
import com.qiniu.pili.droid.shortvideo.PLVideoFilterListener;
import com.qiniu.pili.droid.shortvideo.PLVideoSaveListener;
import com.tsingteng.cosfun.R;
import com.tsingteng.cosfun.app.AppContext;
import com.tsingteng.cosfun.base.BaseVideoActivity;
import com.tsingteng.cosfun.bean.JoinCostarBean;
import com.tsingteng.cosfun.callback.OnCutVideoListener;
import com.tsingteng.cosfun.callback.OnInitGifListener;
import com.tsingteng.cosfun.common.Constant;
import com.tsingteng.cosfun.common.Navigate;
import com.tsingteng.cosfun.crashUtils.utils.FileUtils;
import com.tsingteng.cosfun.crashUtils.utils.LogUtil;
import com.tsingteng.cosfun.helper.ActivityManagers;
import com.tsingteng.cosfun.helper.VideoHelper;
import com.tsingteng.cosfun.ui.costar.publish.VideoPublishActivity;
import com.tsingteng.cosfun.utils.AppUtils;
import com.tsingteng.cosfun.utils.DateUtils;
import com.tsingteng.cosfun.utils.ImageUtils;
import com.tsingteng.cosfun.utils.LogUtils;
import com.tsingteng.cosfun.utils.LogonUtils;
import com.tsingteng.cosfun.utils.RecordSettings;
import com.tsingteng.cosfun.utils.ToastUtils;
import com.tsingteng.cosfun.utils.UIUtils;
import com.tsingteng.cosfun.widget.RecordButton;
import com.tsingteng.cosfun.widget.dialog.BeautifyDialog;
import com.tsingteng.cosfun.widget.PressImageView;
import com.tsingteng.cosfun.widget.dialog.ContentDialog;
import com.tsingteng.cosfun.widget.dialog.CostarHintDialog;
import com.tsingteng.cosfun.widget.dialog.ProgressDialog;
import com.tsingteng.cosfun.widget.dialog.VideoSliceSelectDialog;


import java.io.IOException;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;


/**
 * 描述: 合演 activity
 * 创建人: 肖利
 * 时间: 2018/7/31
 * qq: (872179966)
 */

public class CostarActivity extends BaseVideoActivity implements PLRecordStateListener, PLVideoSaveListener, PLFocusListener,
        View.OnClickListener, VideoSliceSelectDialog.OnDialogDissMissListener, BeautifyDialog.OnDialogDissMissListener {
    private static final String TAG = "CostarActivity";
    private long mDurtion = 60 * 1000;
    private boolean mSectionBegan;
    private PLShortVideoRecorder mShortVideoRecorder;
    private ImageView mSwitchCameraBtn;
    private int isFinish = 0;//是否拍摄完成  -1,拍摄没完成   0  初始化  1，拍摄完成
    private ProgressBar mSectionProgressBar;
    private RecordButton mRecordBtn;
    private GLSurfaceView preview;
    private ImageView mIvClose;

    private LinearLayout llToolsRight;
    private LinearLayout mMeiHua;

    private TextView mTimeCanCos;
    private LinearLayout mVideoCostar;
    private ImageView mIvVideo;
    private TextView mTvTimeShoot;
    private LinearLayout mLocal;
    private boolean switchFlsh = false;
    private RelativeLayout mLlCosTime;
    private long timer = 0;
    private TimerTask taskTimer;
    private Timer timerTask;
    private TextView mTvGaP;

    private int timeMode = 0;
    private TextView mTimeMode;
    private VideoSliceSelectDialog VideoSliceSelectDialog;
    private long videoTime = 0;
    private LinearLayout llCamera;
    private ImageView switchCamera1;
    private ImageView switchShan;
    private RelativeLayout mRlPush;
    private PLShortVideoComposer mShortVideoComposer;
    private PressImageView mIvTime;
    private BeautifyDialog beautifyDialog;
    private String videoAudioPath;
    private FURenderer mFURenderer;
    private int count = 0;
    private Timer countDownTask;
    private TimerTask countDownTimer;

    private byte[] costarData;


    @SuppressLint("HandlerLeak")
    private Handler handler = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 100:
                    if (countDownTask != null) {
                        countDownTask.cancel();
                    }
                    if (countDownTimer != null) {
                        countDownTimer.cancel();
                    }
                    countDownTask = null;
                    countDownTimer = null;
            }
            super.handleMessage(msg);
        }
    };
    private ProgressDialog progressDialog;
    private PLRecordSetting mRecordSetting;


    @Override
    public int getLayoutId() {
        return R.layout.activity_costar;
    }

    private void initVideo() {
        checkPermission(this);

        mShortVideoRecorder = new PLShortVideoRecorder();
        mShortVideoRecorder.setRecordStateListener(this);
        mShortVideoRecorder.setFocusListener(this);

        //摄像头采集

        PLCameraSetting mCameraSetting = new PLCameraSetting();
        PLCameraSetting.CAMERA_FACING_ID facingId = chooseCameraFacingId();
        mCameraSetting.setCameraId(facingId);
        mCameraSetting.setCameraPreviewSizeRatio(PLCameraSetting.CAMERA_PREVIEW_SIZE_RATIO.RATIO_16_9);
        mCameraSetting.setCameraPreviewSizeLevel(PLCameraSetting.CAMERA_PREVIEW_SIZE_LEVEL.PREVIEW_SIZE_LEVEL_480P);
        // 麦克风采集选项(单声道和立体)
        PLMicrophoneSetting mMicrophoneSetting = new PLMicrophoneSetting();
        mMicrophoneSetting.setChannelConfig(AudioFormat.CHANNEL_IN_MONO);
        //视频编码选项
        PLVideoEncodeSetting mVideoEncodeSetting = new PLVideoEncodeSetting(this);
        mVideoEncodeSetting.setEncodingSizeLevel(PLVideoEncodeSetting.VIDEO_ENCODING_SIZE_LEVEL.VIDEO_ENCODING_SIZE_LEVEL_480P_3);
        mVideoEncodeSetting.setEncodingBitrate(VideoHelper.mEncodingBitrate);
        mVideoEncodeSetting.setEncodingFps(25);
        mVideoEncodeSetting.setHWCodecEnabled(true);
        // 音频编码选项
        PLAudioEncodeSetting mAudioEncodeSetting = new PLAudioEncodeSetting();
        mAudioEncodeSetting.setHWCodecEnabled(true);
        mAudioEncodeSetting.setChannels(RecordSettings.AUDIO_CHANNEL_NUM_ARRAY[0]);
        // 录制选项
        // 可以设置最大时长
        mRecordSetting = new PLRecordSetting();
        mRecordSetting.setMaxRecordDuration(mDurtion);
        mRecordSetting.setDisplayMode(PLDisplayMode.FULL);
        mRecordSetting.setVideoCacheDir(VideoHelper.VIDEO_SHOOT);
        mShortVideoComposer = new PLShortVideoComposer(this);

        //创建预览窗口
        mShortVideoRecorder.prepare(preview, mCameraSetting, mMicrophoneSetting, mVideoEncodeSetting,
                mAudioEncodeSetting, null, mRecordSetting);

        if (AppUtils.getSwitchCameraStatus()) {
            mShortVideoRecorder.switchCamera(PLCameraSetting.CAMERA_FACING_ID.CAMERA_FACING_FRONT);
        } else {
            mShortVideoRecorder.switchCamera(PLCameraSetting.CAMERA_FACING_ID.CAMERA_FACING_BACK);
        }
        initBeauty();
        initDialog();
        mRecordBtn.setOnRecordStateChangedListener(new RecordButton.OnRecordStateChangedListener() {
            @Override
            public void onRecordStart() {
                llCamera.setVisibility(View.GONE);
                //做一下判断,当前是否是延时操作
                if (mDurtion < 500) {
                    if (!VideoHelper.getIntence().isFanPai()) {
                        CostarHintDialog costarHintDialog = new CostarHintDialog(CostarActivity.this);
                        costarHintDialog.setContentText(getResources().getString(R.string.can_not_shoot_less_0_5s));
                        costarHintDialog.show();
                        new android.os.Handler().postDelayed(costarHintDialog::dissMiss, 1500);
                        mRecordBtn.endShoot();
                    } else {
                        judgeTimeMode();
                    }
                } else {
                    judgeTimeMode();
                }
            }

            @Override
            public void onRecordStop() {
                llCamera.setVisibility(View.GONE);
                judgeTimeMode();
            }

            @Override
            public void onZoom(float percentage) {

            }
        });
    }

    /**
     * 初始化美颜
     */
    private void initBeauty() {
        mFURenderer = new FURenderer.Builder(AppContext.getContext()).build();

        LogUtils.i("mFURenderer", FURenderer.getVersion() + "<===============");
        mShortVideoRecorder.setVideoFilterListener(new PLVideoFilterListener() {

            @Override
            public void onSurfaceCreated() {
                LogUtils.d(TAG, "mShortVideoRecorder111onSurfaceCreated" + System.currentTimeMillis());
                mFURenderer.loadItems();
            }

            @Override
            public void onSurfaceChanged(int width, int height) {
                LogUtils.d(TAG, "mShortVideoRecorder111onSurfaceChanged" + System.currentTimeMillis());
            }

            @Override
            public void onSurfaceDestroy() {
                LogUtils.d(TAG, "mShortVideoRecorder111onSurfaceDestroy" + System.currentTimeMillis());
                mFURenderer.destroyItems();
                costarData = null;
            }

            @Override
            public int onDrawFrame(int texId, int texWidth, int texHeight, long timeStampNs, float[] transformMatrix) {
                long startTime = new Date().getTime();
                int id;
                if (costarData != null && AppUtils.getBeautyParameterLevel()!=0) {
                    id = mFURenderer.onDrawFrameByFBO(costarData, texId, texWidth, texHeight);
                    long endTime = new Date().getTime();
                    LogUtils.d(TAG, "时间差====>" + String.valueOf(endTime - startTime));

                }else {
                    id = texId;
                }
                return id;
            }
        });

        mShortVideoRecorder.setCameraPreviewListener((data, width, height, rotation, fmt, timestampNs) -> {
            costarData = data;
            return false;
        });
    }



    /**
     * 初始化相关的弹窗
     */
    private void initDialog() {
        VideoSliceSelectDialog = new VideoSliceSelectDialog(this, 1);
        VideoSliceSelectDialog.setOnDialogDissMissListener(this);
        beautifyDialog = new BeautifyDialog(this, mShortVideoRecorder, null, 1);
        beautifyDialog.setOnFaceUnityControlListener(mFURenderer);
        beautifyDialog.setOnDialogDissMissListener(this);
        progressDialog = new ProgressDialog(this);

    }


    private PLCameraSetting.CAMERA_FACING_ID chooseCameraFacingId() {
        if (PLCameraSetting.hasCameraFacing(PLCameraSetting.CAMERA_FACING_ID.CAMERA_FACING_3RD)) {
            return PLCameraSetting.CAMERA_FACING_ID.CAMERA_FACING_3RD;
        } else if (PLCameraSetting.hasCameraFacing(PLCameraSetting.CAMERA_FACING_ID.CAMERA_FACING_FRONT)) {
            return PLCameraSetting.CAMERA_FACING_ID.CAMERA_FACING_FRONT;
        } else {
            return PLCameraSetting.CAMERA_FACING_ID.CAMERA_FACING_BACK;
        }
    }

    @Override
    public void initView() {
        mRecordBtn = findViewById(R.id.recordButton);
        mSwitchCameraBtn = findViewById(R.id.switch_camera);
        mSectionProgressBar = findViewById(R.id.record_progressbar);
        preview = findViewById(R.id.preview);
        mIvClose = findViewById(R.id.iv_close);
        llToolsRight = findViewById(R.id.ll_tools_right);
        mMeiHua = findViewById(R.id.ll_mh);
        mTimeCanCos = findViewById(R.id.tv_can_cos);
        mVideoCostar = findViewById(R.id.ll_video_costar);
        mIvVideo = findViewById(R.id.iv_video);
        mTvTimeShoot = findViewById(R.id.tv_time_shoot);
        mLocal = findViewById(R.id.ll_local);
        mLlCosTime = findViewById(R.id.ll_cos_time);
        mTvGaP = findViewById(R.id.tv_gp_time);
        mTimeMode = findViewById(R.id.tv_time_mode);
        llCamera = findViewById(R.id.ll_report_camera);
        switchCamera1 = findViewById(R.id.switch_camera1);
        switchShan = findViewById(R.id.switch_shan);
        mRlPush = findViewById(R.id.rl_push);
        mIvTime = findViewById(R.id.iv_time);
        findViewById(R.id.pr_mei_hua).setOnClickListener(this);
        mSwitchCameraBtn.setOnClickListener(this);
        mRecordBtn.setOnClickListener(this);
        mIvClose.setOnClickListener(this);
        mMeiHua.setOnClickListener(this);
        mLocal.setOnClickListener(this);
        mLlCosTime.setOnClickListener(this);
        mIvVideo.setOnClickListener(this);
        switchCamera1.setOnClickListener(this);
        switchShan.setOnClickListener(this);
        mRlPush.setOnClickListener(this);
        preview.setOnClickListener(this);


        //长安显示山关灯
        switchCamera1.setOnLongClickListener(v -> {
            if (llCamera.getVisibility() == View.GONE) {
                llCamera.setVisibility(View.VISIBLE);
                if (AppUtils.getSwitchCameraStatus()) {
                    switchShan.setEnabled(false);
                    switchShan.setImageDrawable(getResources().getDrawable(R.drawable.flash_close_icon_press));
                } else {
                    switchShan.setEnabled(true);
                    if (switchFlsh) {
                        switchShan.setImageDrawable(getResources().getDrawable(R.drawable.flash_icon));
                    } else {
                        switchShan.setImageDrawable(getResources().getDrawable(R.drawable.flash_close_icon));
                    }
                }
                switchCamera1.setImageDrawable(getResources().getDrawable(R.drawable.turn_click_icon));
            } else {
                switchCamera1.setImageDrawable(getResources().getDrawable(R.drawable.turn_icon));
                llCamera.setVisibility(View.GONE);
            }
            return true;
        });

        initVideo();
    }

    @Override
    protected void getIntentData(Intent intent) {

    }

    /**
     * 根据拍摄的模式显示隐藏相关的控件,加载相应的资源
     */
    public void initShootMode() {
        mShortVideoRecorder.setMusicFile(null);
        long haveUseTime = VideoHelper.getIntence().getVideoListTime();
        //若果是翻拍的话currentPosition 肯定不是-1
        if (VideoHelper.getIntence().isFanPai()) {
            mDurtion = VideoHelper.getIntence().getVideoTimeByIndex(VideoHelper.getIntence().getCurrentVideoPosition()) + VideoHelper.MORE_DURTION_TIME;
            videoAudioPath = VideoHelper.getIntence().getVideoAudioPath();
            new Handler().postDelayed(() -> mShortVideoRecorder.setMusicFile(videoAudioPath), 200);
        } else if (VideoHelper.getIntence().getCurrentVideoPosition() != -1) {//不是原生翻拍的时候如果不等于-1的话,肯定是自己翻拍
            mDurtion = 60 * 1000 - haveUseTime + VideoHelper.getIntence().getVideoTimeByIndex(VideoHelper.getIntence().getCurrentVideoPosition());
        } else {//都不是的时候,就是加一段视屏
            mDurtion = 60 * 1000 - haveUseTime;
        }
        if (haveUseTime != 0) {//说明已经拍摄了视屏
            mVideoCostar.setVisibility(View.VISIBLE);
            mIvVideo.setVisibility(View.VISIBLE);
            mRlPush.setVisibility(View.VISIBLE);
            mTvTimeShoot.setVisibility(View.VISIBLE);
            int currentVideoPosition = VideoHelper.getIntence().getViewPosition();
            String videoCoverUrl = VideoHelper.getIntence().getVideoPathByIndex(currentVideoPosition == -1 ? 0 : VideoHelper.getIntence().getViewPosition());
            if (TextUtils.isEmpty(videoCoverUrl)) {
                mIvVideo.setImageDrawable(getResources().getDrawable(R.drawable.add_fragment));
            } else {
                ImageUtils.LoadImage(this, videoCoverUrl, mIvVideo);
            }
        } else {//还没有视屏
            mVideoCostar.setVisibility(View.INVISIBLE);
            mIvVideo.setVisibility(View.INVISIBLE);
            mRlPush.setVisibility(View.GONE);
        }
        //重新设置拍摄时间和拍摄路径
        if (isFinish==0 || isFinish==1) {
            mShortVideoRecorder.deleteAllSections();
        }else {
            mRecordBtn.endShoot();
            starCosfun();

        }
        if (mDurtion < 0) mDurtion = 0;
        mRecordSetting.setMaxRecordDuration(mDurtion);
        mShortVideoRecorder.setRecordSpeed(1);
        mRecordSetting.setVideoFilepath(VideoHelper.VIDEO_SHOOT + System.currentTimeMillis() + LogonUtils.getProFildId() + "cos_fun.mp4");
        llToolsRight.setVisibility(View.VISIBLE);
        //隐藏相关的控件
        mTimeCanCos.setText(String.format(getResources().getString(R.string.can_shoot_time), DateUtils.div(mDurtion, 1000, 1)));
        mSectionProgressBar.setMax((int) mDurtion);
        setVisibility(View.VISIBLE, mIvClose, mTimeCanCos, mTvTimeShoot, switchCamera1, mLlCosTime, mSwitchCameraBtn, mMeiHua);
        setVisibility(View.GONE, mTvGaP);
        mLocal.setVisibility(VideoHelper.getIntence().isFanPai() ? View.INVISIBLE : View.VISIBLE);
        JoinCostarBean joinCostarBean = VideoHelper.getIntence().getJoinCostarBean();
        if (joinCostarBean != null) {
            if (!joinCostarBean.isModification()) {
                //隐藏发布按钮
                mRlPush.setVisibility(View.GONE);
            } else {
                mRlPush.setVisibility(View.VISIBLE);
            }
        }

    }

//    /**
//     * 半屏
//     */
//    private void cranScreen() {
//        RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
//        layoutParams.setMargins(0, AppUtils.getScreenWidthAndHeight(this)[1] / 100 * 17, 0, AppUtils.getScreenWidthAndHeight(this)[1] / 100 * 29);
//        preview.setLayoutParams(layoutParams);
//    }

    /**
     * 开始拍摄
     */
    private void starCosfun() {
        if (!mSectionBegan && mShortVideoRecorder.beginSection()) {
            mTimeMode.setVisibility(View.GONE);
            isFinish = -1;
            changeUI(1);
            startTimer();
            mSectionBegan = true;
            mRecordBtn.setEnabled(true);
            updateRecordingBtns(true);
        } else {
            mRecordBtn.setEnabled(false);
            destoryTimer();
            changeUI(2);
            mShortVideoRecorder.endSection();
            LogUtils.i("endSection");
            mSectionBegan = false;
            isFinish = 1;
            mShortVideoRecorder.concatSections(CostarActivity.this);
            if (progressDialog == null) progressDialog = new ProgressDialog(this);
            progressDialog.show();
        }
    }

    /**
     * 更改ui
     */
    private void changeUI(int i) {
        switch (i) {
            case 1:
                mTvGaP.setText(getResources().getString(R.string.second_0));
                setVisibility(View.INVISIBLE, mTvTimeShoot, switchCamera1, mLlCosTime, mRlPush, mIvClose, mLocal, llToolsRight, mIvVideo, mSwitchCameraBtn, mTimeCanCos);//隐藏控件
                setVisibility(View.VISIBLE, mRecordBtn, mTvGaP);
                break;
            case 2:
                break;
        }


    }

    /**
     * 隐藏显示事件
     *
     * @param visibility f
     * @param views      f
     */
    private void setVisibility(int visibility, View... views) {
        for (View view : views) {
            view.setVisibility(visibility);
        }
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case PictureConfig.TYPE_VIDEO:
                    // 图片、视频、音频选择结果回调
                    List<LocalMedia> selectList = PictureSelector.obtainMultipleResult(data);
                    // 例如 LocalMedia 里面返回三种path
                    // 1.media.getPath(); 为原图path
                    // 2.media.getCutPath();为裁剪后path，需判断media.isCut();是否为true  注意：音视频除外
                    // 3.media.getCompressPath();为压缩后path，需判断media.isCompressed();是否为true  注意：音视频除外
                    // 如果裁剪并压缩了，以取压缩路径为准，因为是先裁剪后压缩的
                    LocalMedia localMedia = selectList.get(0);
                    if (!TextUtils.isEmpty(localMedia.getPath())) {
                        if (localMedia.getDuration() > (1000 * 60 * 30)) {
                            showHintDialog("视频大于30分钟,请重新选择!");
                            return;
                        }
                        String desPath = VideoHelper.VIDEO_SHOOT + System.currentTimeMillis() + LogonUtils.getProFildId() + "cos_fun.mp4";
                        try {
                            FileUtils.copyFile2DestPath(localMedia.getPath(), desPath);
                        } catch (IOException e) {
                            e.printStackTrace();
                            ToastUtils.showToast("视屏拷贝失败!");
                            return;
                        }
                        Intent intent = new Intent(CostarActivity.this, PreViewActivity.class);
                        intent.putExtra(VideoHelper.VIDEO_PATH, desPath);
                        intent.putExtra(VideoHelper.VIDEO_LOCAL, true);
                        startActivity(intent);
                        isFinish = 1;
                    }
                    break;
                case Constant.REQUESTCODE:
                    finish();
                    break;
            }
        }
    }


    /**
     * 设置
     */
    private void updateRecordingBtns(boolean isRecording) {
        mSwitchCameraBtn.setEnabled(!isRecording);
        mRecordBtn.setActivated(isRecording);
    }

    @Override
    protected void onResume() {
        super.onResume();
        mRecordBtn.setEnabled(false);
//        if (mSectionBegan) {
//            mShortVideoRecorder.beginSection();
//        }
        mShortVideoRecorder.resume();
        if (isFinish==1) {
            recoverData();
        }
        refreshFilter();
        initShootMode();
    }

    private void refreshFilter() {
        //刷新滤镜
        int beautyFilterLevel = AppUtils.getBeautyFilterLevel();
        if (beautyFilterLevel != -1) {
            PLBuiltinFilter[] builtinFilterList = mShortVideoRecorder.getBuiltinFilterList();
            List<PLBuiltinFilter> plBuiltinFilters = Arrays.asList(builtinFilterList);
            PLBuiltinFilter plBuiltinFilter = plBuiltinFilters.get(beautyFilterLevel);
            mShortVideoRecorder.setBuiltinFilter(plBuiltinFilter.getName());
        }
    }

    /**
     * 初始状态
     */
    public void recoverData() {
        if (mShortVideoRecorder != null)
            mShortVideoRecorder.deleteAllSections();
        timer = 0;
        mSectionProgressBar.setProgress(0);

    }

    @Override
    protected void onPause() {

        updateRecordingBtns(false);
        mShortVideoRecorder.pause();

        LogUtils.d("xiaoli + onPause");
        super.onPause();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mShortVideoRecorder.destroy();
        mShortVideoComposer = null;
        destoryTimer();
        LogUtils.d("xiaoli + onDestroy");
    }

    @Override
    public void onManualFocusStart(boolean result) {
    }

    @Override
    public void onManualFocusStop(boolean result) {
        Log.i(TAG, "manual focus end result: " + result);

    }

    @Override
    public void onManualFocusCancel() {
        Log.i(TAG, "manual focus canceled");
    }

    @Override
    public void onAutoFocusStart() {
        Log.i(TAG, "auto focus start");
    }

    @Override
    public void onAutoFocusStop() {
        Log.i(TAG, "auto focus stop");

    }

    @Override
    public void onReady() {
        runOnUiThread(() -> {
            mRecordBtn.setEnabled(true);
//                ToastUtils.showToast("可以开始拍摄咯");
        });

    }

    @Override
    public void onError(int i) {
    }

    @Override
    public void onDurationTooShort() {
        runOnUiThread(() -> {
            AppUtils.showHintDialogToast(CostarActivity.this, "时间太短了!");
            mRecordBtn.setEnabled(true);
        });
    }

    @Override
    public void onRecordStarted() {
        Log.i(TAG, "record onRecordStarted time: " + System.currentTimeMillis());
        //开始拍摄
    }

    @Override
    public void onSectionRecording(long l, long l1, int i) {

    }


    @Override
    public void onRecordStopped() {
        Log.i(TAG, "record stop time: " + System.currentTimeMillis());
        runOnUiThread(() -> updateRecordingBtns(false));
    }

    //当有新片段录制完成时触发
    @Override
    public void onSectionIncreased(long l, long l1, int i) {
        Log.i(TAG, "record onSectionIncreased time: " + l + "===" + l1 + "==" + i);
        //记录每段的视屏时间
        videoTime = l;
    }

    // 当有片段被删除时触发
    @Override
    public void onSectionDecreased(long l, long l1, int i) {

    }

    @Override
    public void onRecordCompleted() {

        runOnUiThread(() -> {
//                showToast("已达到拍摄时长!");
            if (taskTimer != null)
                timerTask.cancel();
            changeUI(2);
            isFinish = 1;
            mSectionBegan = false;
            destoryTimer();
            llCamera.setVisibility(View.GONE);
            mRecordBtn.endShoot();
            if (progressDialog == null)
                progressDialog = new ProgressDialog(CostarActivity.this);
            progressDialog.show();
            new Handler().postDelayed(() -> {
                mShortVideoRecorder.endSection();
                mShortVideoRecorder.concatSections(CostarActivity.this);
            }, 200);
        });
    }


    @Override
    public void onSaveVideoSuccess(final String filePath) {
        progressDialog.disMissDialog();
        if (!VideoHelper.getIntence().isFanPai()) {
            progressDialog.disMissDialog();
            toPreViewActivity(filePath);
            return;
        }
        Log.i(TAG, "record onSaveVideoSuccess time: " + filePath + System.currentTimeMillis());
        runOnUiThread(() -> {
            progressDialog.disMissDialog();
            VideoHelper.getIntence().cutPreVideo(CostarActivity.this, filePath, new OnCutVideoListener() {
                @Override
                public void cutVideoStart() {
                    runOnUiThread(() -> {
                        if (progressDialog == null)
                            progressDialog = new ProgressDialog(CostarActivity.this);
                        progressDialog.setmProgressbar(0);
                        progressDialog.show();
                    });

                }

                @Override
                public void cutVideoSuccess(String url) {
                    runOnUiThread(() -> {
                        progressDialog.disMissDialog();
                        toPreViewActivity(url);
                    });

                }

                @Override
                public void cutVideoFail(int code) {
                    runOnUiThread(() -> progressDialog.disMissDialog());
                }

                @Override
                public void cutVideoCancel() {
                    runOnUiThread(() -> progressDialog.disMissDialog());

                }

                @Override
                public void cutVideoProgress(int progress) {
                    runOnUiThread(() -> progressDialog.setmProgressbar(progress));

                }
            });

        });
    }

    /**
     * 去预览页
     */
    private void toPreViewActivity(String filePath) {
        Intent intent = new Intent(CostarActivity.this, PreViewActivity.class);
        intent.putExtra(VideoHelper.VIDEO_PATH, filePath);
        intent.putExtra(VideoHelper.VIDEO_TIME, videoTime);
        startActivityForResult(intent, Constant.REQUESTCODE);
    }

    @Override
    public void onSaveVideoFailed(final int errorCode) {
        Log.i(TAG, "record onSaveVideoFailed time: " + System.currentTimeMillis());
        runOnUiThread(() -> {
            progressDialog.disMissDialog();
            mRecordBtn.setEnabled(true);
//                ToastUtils.showToast("baocun 视频段失败: " + errorCode);
        });
    }

    @Override
    public void onSaveVideoCanceled() {
        Log.i(TAG, "record onSaveVideoFailed time: " + System.currentTimeMillis());
        progressDialog.disMissDialog();

    }

    @Override
    public void onProgressUpdate(final float percentage) {
        Log.i(TAG, "record onSaveVideoFailed time: " + System.currentTimeMillis());
        runOnUiThread(() -> progressDialog.setmProgressbar((int) (100 * percentage)));
    }


    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.switch_camera1:
            case R.id.switch_camera:
                LogUtil.d("BugReporter", "switch_camera");
                if (AppUtils.getSwitchCameraStatus()) {
                    AppUtils.setSwitchCameraStatus(false);
                    switchShan.setEnabled(true);
                    switchShan.setImageDrawable(getResources().getDrawable(R.drawable.flash_close_icon));
                } else {
                    AppUtils.setSwitchCameraStatus(true);
                    switchShan.setEnabled(false);
                    switchShan.setImageDrawable(getResources().getDrawable(R.drawable.flash_close_icon_press));
                }
                mShortVideoRecorder.switchCamera();
                refreshFilter();
                break;


            case R.id.switch_shan:
                LogUtil.d("BugReporter", "switch_shan");
                if (switchFlsh) {
                    mShortVideoRecorder.setFlashEnabled(false);
                    switchShan.setImageDrawable(getResources().getDrawable(R.drawable.flash_close_icon));
                } else {
                    mShortVideoRecorder.setFlashEnabled(true);
                    switchShan.setImageDrawable(getResources().getDrawable(R.drawable.flash_icon));
                }
                switchFlsh = !switchFlsh;
                break;
            case R.id.iv_close:
                LogUtil.d("BugReporter", "iv_close");
                affirmDialog();
                break;
            case R.id.pr_mei_hua:
            case R.id.ll_mh:
                LogUtil.d("BugReporter", "ll_mh");
                if (beautifyDialog == null) {
                    beautifyDialog = new BeautifyDialog(this, mShortVideoRecorder, null, 1);
                    beautifyDialog.setOnDialogDissMissListener(this);
                }
                beautifyDialog.show();
                setVisibility(View.GONE, mMeiHua, mLocal, mTimeCanCos, mLlCosTime, mVideoCostar, mSectionProgressBar);
                break;
            case R.id.pr_local:
            case R.id.ll_local:
                LogUtil.d("BugReporter", "ll_local");
                Navigate.startLocalVideo(this);
//                startActivity(new Intent(this, CommonActivity.class).putExtra(CommonActivity.FRAGMENT_KEY, CommonActivity.KEY_LOCAL_VIDEO));
                break;
            case R.id.iv_time:
            case R.id.ll_cos_time:
                LogUtil.d("BugReporter", "ll_cos_time");
                if (timeMode == 0) {
                    mIvTime.setImageDrawable(getResources().getDrawable(R.drawable.time_3s_icon));
                } else if (timeMode == 3) {
                    mIvTime.setImageDrawable(getResources().getDrawable(R.drawable.time_10s_icon));
                } else {
                    mIvTime.setImageDrawable(getResources().getDrawable(R.drawable.timely_icon));
                }
                timeMode();
                break;
            case R.id.iv_video:
                LogUtil.d("BugReporter", "iv_video");
                //选择片段
                if (VideoSliceSelectDialog == null) {
                    VideoSliceSelectDialog = new VideoSliceSelectDialog(this, 1);
                    VideoSliceSelectDialog.setOnDialogDissMissListener(this);
                }
                VideoSliceSelectDialog.show();
                new Handler().postDelayed(() -> VideoSliceSelectDialog.refreshData(), 50);

                break;
            case R.id.rl_push:
                LogUtil.d("BugReporter", "rl_push");
                conposeVideo();
                break;
            case R.id.preview:
                LogUtil.d("BugReporter", "preview");
                if (llCamera.getVisibility() == View.VISIBLE) {
                    switchCamera1.setImageDrawable(getResources().getDrawable(R.drawable.turn_icon));
                    llCamera.setVisibility(View.GONE);
                }
                break;

        }
    }

    /**
     * 确认弹窗
     */
    private void affirmDialog() {
        LogUtil.d("BugReporter", "affirmDialog");
        if (VideoHelper.getIntence().getVideoInfoSize() == 0) {
            finish();
            overridePendingTransition(R.anim.activity_up_alpha, R.anim.activity_down);
        } else if (VideoHelper.getIntence().getJoinCostarBean() != null && !VideoHelper.getIntence().getJoinCostarBean().isModification()) {
            finish();
            overridePendingTransition(R.anim.activity_up_alpha, R.anim.activity_down);
        } else {
            new ContentDialog(this).setContent("确定要放弃当前录制吗?").setCancelContent("取消")
                    .setAffirmContent("放弃").setAffirmContentColor(R.color.red_bag_color)
                    .setOnTwoClickListener(new ContentDialog.OnTwoClickListener() {
                        @Override
                        public void onAffirm() {
//                            finish();
                            ActivityManagers.getInstance().delShootActivity();
                            overridePendingTransition(R.anim.activity_up_alpha, R.anim.activity_down);
                        }

                        @Override
                        public void onCancel() {

                        }
                    }).show();
        }

    }

    private void conposeVideo() {
        LogUtil.d("BugReporter", "conposeVideo");
        if (VideoHelper.getIntence().getVideoListTime() < 5000) {
            CostarHintDialog costarHintDialog = new CostarHintDialog(this);
            costarHintDialog.show();
            new Handler().postDelayed(costarHintDialog::dissMiss, 1500);
            return;
        }
        //清空一下保存的空片段
        if (!VideoHelper.getIntence().clearEmptyVideoPath()) {
            CostarHintDialog costarHintDialog = new CostarHintDialog(this);
            costarHintDialog.setContentText(getResources().getString(R.string.video_publish_fail));
            costarHintDialog.show();
            postDelayed(costarHintDialog::dissMiss, 1500);
        } else {
            PLVideoEncodeSetting setting = new PLVideoEncodeSetting(this);
            setting.setEncodingSizeLevel(PLVideoEncodeSetting.VIDEO_ENCODING_SIZE_LEVEL.VIDEO_ENCODING_SIZE_LEVEL_480P_3);
            setting.setEncodingBitrate(VideoHelper.mEncodingBitrate);
            setting.setEncodingFps(22);
            List<String> list = VideoHelper.getIntence().getVideoPathList();
            if (progressDialog == null) progressDialog = new ProgressDialog(this);
            progressDialog.show();
            if (list.size() == 1) {
                initRotateView();
            } else {
                mShortVideoComposer.composeVideos(list, VideoHelper.VIDEO_COMPOSED + System.currentTimeMillis() + "compose.mp4", setting, mVideoSaveListener);
            }
        }
    }

    private void initRotateView() {
        LogUtil.d("BugReporter", "initRotateView");
        PLShortVideoTranscoder mShortVideoTranscoder = new PLShortVideoTranscoder(getApplicationContext(), VideoHelper.getIntence().getVideoSectionBeanList().get(0).getLocalUrl(), VideoHelper.VIDEO_SHOOT + System.currentTimeMillis() + "cos_fun.mp4");
        // 获取源视频宽度
        int srcWidth = mShortVideoTranscoder.getSrcWidth();
        // 获取源视频高度
        int srcHeight = mShortVideoTranscoder.getSrcHeight();
        // 获取源视频码率
        int srcBitrate = VideoHelper.mEncodingBitrate;
        if (progressDialog == null) progressDialog = new ProgressDialog(this);
        progressDialog.show();
        mShortVideoTranscoder.transcode(srcWidth, srcHeight, srcBitrate, new PLVideoSaveListener() {
            @Override
            public void onSaveVideoSuccess(String destFile) {
                runOnUiThread(() -> {
                    LogUtil.d("BugReporter", "onSaveVideoSuccess");
                    progressDialog.disMissDialog();
//                    mLlProgress.setVisibility(View.GONE);
                    ToVideoPush(destFile);
                });
            }

            @Override
            public void onSaveVideoFailed(int i) {
                LogUtil.d("BugReporter", "onSaveVideoFailed");
                progressDialog.disMissDialog();
            }

            @Override
            public void onSaveVideoCanceled() {
                UIUtils.runOnUIThread(() -> {
                    LogUtil.d("BugReporter", "onSaveVideoCanceled");
                    progressDialog.disMissDialog();
                });

            }

            @Override
            public void onProgressUpdate(float percentage) {
                UIUtils.runOnUIThread(() -> {
                    LogUtil.d("BugReporter", "onProgressUpdate");
                    if ((int) (100 * percentage) <= 100)
                        progressDialog.setmProgressbar((int) (100 * percentage));
                });
            }
        });


    }

    private void judgeTimeMode() {
        LogUtil.d("BugReporter", "judgeTimeMode");
        if (mSectionBegan) {
            starCosfun();
        } else {
            if (timeMode == 0) {
                starCosfun();
                return;
            }
            changeUI(1);
            mTimeMode.setText(String.valueOf(timeMode));
            mTimeMode.setVisibility(View.VISIBLE);
            mRecordBtn.setEnabled(false);
            count = timeMode;
            countDownTask = new Timer();

            countDownTimer = new TimerTask() {
                @Override
                public void run() {
                    runOnUiThread(() -> {
                        LogUtils.e("countDownTimer", count + "");
                        if (count == 1) {
                            mTimeMode.setVisibility(View.GONE);
                            starCosfun();
                            Message message = handler.obtainMessage();
                            message.what = 100;
                            handler.sendMessage(message);
                        } else {
                            count--;
                            mTimeMode.setText(String.valueOf(count));
                        }

                    });
                }
            };
            countDownTask.schedule(countDownTimer, 1000, 1000);

        }

    }

    private void timeMode() {
        LogUtil.d("BugReporter", "timeMode");
        if (timeMode == 0) {
            timeMode = 3;
            AppUtils.showHintDialogToast(this, "延时3秒");
        } else if (timeMode == 3) {
            timeMode = 10;
            AppUtils.showHintDialogToast(this, "延时10秒");
        } else {
            timeMode = 0;
            AppUtils.showHintDialogToast(this, "不延时");
        }


    }

    public void startTimer() {
        LogUtil.d("BugReporter", "startTimer");
        timerTask = new Timer();
        taskTimer = new TimerTask() {
            @Override
            public void run() {
                runOnUiThread(() -> {
                    LogUtils.e("taskTimer", timer + "");
                    timer = timer + 10;
                    mTvGaP.setText(String.format(getResources().getString(R.string.shoot_time), DateUtils.div(timer, 1000, 1)));
                    mSectionProgressBar.setProgress((int) timer);
                });
            }
        };
        timerTask.schedule(taskTimer, 0, 10);
    }

    private void destoryTimer() {
        LogUtil.d("BugReporter", "destoryTimer");
        if (taskTimer != null) {
            taskTimer.cancel();
            taskTimer = null;
        }
        if (timerTask != null) {
            timerTask.cancel();
            timerTask = null;
        }
    }


    public static void checkPermission(Context context) {
        LogUtils.i("checkPermission");
        if (ContextCompat.checkSelfPermission(context, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED ||
                ContextCompat.checkSelfPermission(context, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED ||
                ContextCompat.checkSelfPermission(context, Manifest.permission.RECORD_AUDIO) != PackageManager.PERMISSION_GRANTED) {
            Log.e(TAG, "no permission");
            ActivityCompat.requestPermissions((Activity) context,
                    new String[]{Manifest.permission.CAMERA,
                            Manifest.permission.WRITE_EXTERNAL_STORAGE,
                            Manifest.permission.RECORD_AUDIO}, 0);
        }
    }

    private PLVideoSaveListener mVideoSaveListener = new PLVideoSaveListener() {
        @Override
        public void onSaveVideoSuccess(final String destFile) {
            UIUtils.runOnUIThread(() -> {
                LogUtil.d("BugReporter", "onSaveVideoSuccess");
                progressDialog.disMissDialog();
//                    mLlProgress.setVisibility(View.GONE);
                ToVideoPush(destFile);
            });
        }

        @Override
        public void onSaveVideoFailed(int errorCode) {
            UIUtils.runOnUIThread(() -> {
                LogUtil.d("BugReporter", "onSaveVideoFailed");
                progressDialog.disMissDialog();
            });

        }

        @Override
        public void onSaveVideoCanceled() {
            UIUtils.runOnUIThread(() -> {
                LogUtil.d("BugReporter", "onSaveVideoCanceled");
                progressDialog.disMissDialog();
            });

        }


        @Override
        public void onProgressUpdate(final float percentage) {
            UIUtils.runOnUIThread(() -> {
                LogUtils.i("onProgressUpdate" + percentage);
                LogUtil.d("BugReporter", "onProgressUpdate");
//                    mCcpProgress.setProgress((int) (100 * percentage));
//                    mTvProgress.setText((int) (100 * percentage) + "%");
                if ((int) (100 * percentage) <= 100)
                    progressDialog.setmProgressbar((int) (100 * percentage));
            });
        }
    };

    private void ToVideoPush(String destFile) {
        LogUtil.d("BugReporter", "ToVideoPush");
        //将主视屏保存
        VideoHelper.getIntence().addMainVideoInfo(destFile);
        VideoHelper.getIntence().initGif(this, mShortVideoComposer, new OnInitGifListener() {
            @Override
            public void onStartGif() {
                if (progressDialog == null)
                    progressDialog = new ProgressDialog(CostarActivity.this);
                progressDialog.show();
                progressDialog.setmProgressbar(50);

            }

            @Override
            public void onSuccessGif() {
                progressDialog.disMissDialog();
                toPublishVideo();
            }

            @Override
            public void onFailGif() {
                progressDialog.disMissDialog();
                toPublishVideo();
            }

            @Override
            public void onProgress(int progress) {
                progressDialog.setmProgressbar(progress);
            }
        });
    }

    private void toPublishVideo() {
        LogUtil.d("BugReporter", "toPublishVideo");
        Intent intent = new Intent(CostarActivity.this, VideoPublishActivity.class);
        startActivityForResult(intent, Constant.REQUESTCODE);
        mRlPush.setEnabled(true);
        onPause();//再次关闭资源
    }


    @Override
    public void onBackPressed() {
        LogUtil.d("BugReporter", "onBackPressed");
        affirmDialog();
    }

    @Override
    public void onDissMiss() {
        LogUtil.d("BugReporter", "onDissMiss");
        initShootMode();
    }

    public void showSliceSelectDialog() {
        LogUtil.d("BugReporter", "showSliceSelectDialog");
        if (VideoSliceSelectDialog == null) return;
        VideoSliceSelectDialog.refreshData();

    }

    public void dissSliceSelectDialog() {
        LogUtil.d("BugReporter", "dissSliceSelectDialog");
        if (VideoSliceSelectDialog == null) return;
        VideoSliceSelectDialog.dissMiss();
    }


    @Override
    public void dissMissClick() {
        LogUtil.d("BugReporter", "dissMissClick");
        setVisibility(View.VISIBLE, mMeiHua, mLocal, mTimeCanCos, mLlCosTime, mVideoCostar, mSectionProgressBar);
    }
}
